import React from "react";
import { View, Text, Picker, Image } from '@tarojs/components'
import styles from "./index.module.scss";
import { AtButton, AtList, AtListItem } from 'taro-ui'
import { BaseComponents, Layout } from "@/components";
import { loginApi, updateUserinfoApi } from '@/api';
import Taro from '@tarojs/taro'



interface Props { }
interface State {
  dateSel: string
}

export default class Index extends BaseComponents<Props, State> {

  constructor(props: Props) {
    super(props);

    this.state = {
      dateSel: ''
    };
  }

  componentWillMount() { }

  componentDidMount() {
    if (Taro.getStorageSync('token')) {
      Taro.switchTab({url:'/pages/index/index'});
    }
  }

  componentWillUnmount() { }

  componentDidShow() { }

  componentDidHide() { }

  login = () => {
    Taro.getUserProfile({
      desc: '展示用户信息',
      success: function (res) {
        const userInfo = res.userInfo;
        //存储等操作
        Taro.login({
          success: async (res: any) => {
            //获取open_id和session_id
            // let code=await loginCode(res.code);
            loginApi({ code: res.code }).then((res: any) => {
              Taro.setStorageSync('token', res.token);
              Taro.switchTab({ url: '/pages/index/index' });
              const obj = {
                alias: userInfo.nickName,
                avatar: userInfo.avatarUrl,
                gender: userInfo.gender,
                code: res.user.code
              }
              updateUserinfoApi(obj).then((res: any) => {
                Taro.setStorageSync('userInfo', res);
              });
            });
          }
        })
      },
      fail(res) {
        Taro.showToast({
          icon: 'none',
          title: '请先授权登录'
        })
      }
    })
  }
  getPhoneNumber = (e) => {
    console.log(e)
    console.log(`是否成功调用${e.detail.errMsg}`);
    console.log(`加密算法的初始向量:${e.detail.iv}`);
    console.log(`包括敏感数据在内的完整用户信息的加密数据:${e.detail.encryptedData}`);
  }

  render() {
    return (
      <Layout tabBar navBar title="登录">
        <View className={styles.index}>
          <AtButton type='primary' onClick={() => { this.login() }}>快捷登录</AtButton>
          {/* <AtButton openType='getUserInfo'
onGetUserInfo={this.login.bind(this)}>微信快速登录</AtButton> */}
          {/* <AtButton openType='getPhoneNumber'
onGetPhoneNumber={this.getPhoneNumber.bind(this)}>微信快速登录</AtButton> */}
        </View>
      </Layout>
    )
  }
}
